﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using Chaine.Models;
using MongoDB.Bson;
using System.IO;

namespace Chaine.DAO
{
    public class EventManager
    {
        private static MongoCollection<EventModels> _Events;
        private static MongoCollection<EventModels> Events
        {
            get
            {
                if (_Events != null)
                    return _Events;
                _Events = DAO.DB.GetDBInstance().GetCollection<EventModels>("Events");
                return _Events;
            }
        }

        /// <summary>
        /// 返回所有活动
        /// </summary>
        /// <returns></returns>
        public static List<EventModels> GetEvents()
        {
            var result = Events.Find(Query.EQ("IsDeleted", false)).ToList();
            return result == null ? new List<EventModels>() : result.OrderByDescending(r => r.StartDateTime).ToList();
        }

        public static List<EventModels> GetEvents(string year)
        {
            var result = Events.Find(Query.Matches("StartDate", ".*" + year + ".*")).Where(e => !e.IsDeleted);
            return result == null ? new List<EventModels>() : result.OrderByDescending(r => r.StartDateTime).ToList();
        }

        public static EventModels GetEvent(string date)
        {
            var year = date.Substring(0, 4);
            var month = date.Substring(4, 2);
            var day = date.Substring(6, 2);
            var result = Events.FindOne(Query.EQ("StartDate", string.Format(@"{0}/{1}/{2}", month, day, year)));
            return result;
        }

        public static EventModels GetEvent(ObjectId id)
        {
            return Events.FindOne(Query.EQ("_id", id));
        }

        /// <summary>
        ///  最近的活动
        /// </summary>
        /// <returns></returns>
        public static EventModels GetLatestEvent()
        {
            var events = Events.Find(Query.GTE("StartDateTime", DateTime.Now)).SetSortOrder(SortBy.Ascending("StartDateTime")).Where(e => !e.IsDeleted);
            if (events == null || events.Count() == 0)
                return null;

            var result = events.First();

            return result;
        }

        /// <summary>
        /// 创建活动
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static bool CreateEvent(EventModels e)
        {
            return Events.Insert(e).Ok;
        }

        public static List<int> GetYear()
        {
            var result = new List<int>();
            var events = GetEvents();
            var max = events.Max(e => e.StartDateTime).Year;
            var min = events.Min(e => e.StartDateTime).Year;
            for (int i = max; i >= min; i--)
            {
                result.Add(i);
            }
            return result;
        }

        /// <summary>
        /// 更新活动信息
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static bool UpdateEvent(EventModels e)
        {
            return Events.Save(e).Ok;
        }

        /// <summary>
        /// 删除活动信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool DeleteEvent(ObjectId id)
        {
            var e = GetEvent(id);
            if (e == null)
                return false;
            e.IsDeleted = true;
            return Events.Save(e).Ok;
        }

        public static List<string> GetPhotosFileName(string date)
        {
            var e = GetEvent(date);
            if (e == null)
                return new List<string>();
            var dirPath = HttpContext.Current.Server.MapPath("/events/photo/" + date + "/photos/");
            if (!Directory.Exists(dirPath))
                return new List<string>();
            var files = Directory.GetFiles(dirPath).Select(f => new FileInfo(f)).OrderByDescending(f => f.LastWriteTime).Select(f => f.Name).ToList();
            return files;
        }

        /// <summary>
        /// 获取将要举行的活动
        /// </summary>
        /// <returns></returns>
        public static List<EventModels> GetComingUpEvents()
        {

            var result = Events.Find(Query.GTE("StartDateTime", DateTime.Now)).Where(e => !e.IsDeleted).ToList();
            return result;
        }
    }
}